// var WebSocketServer = require('websocket').server;
// var http = require('http');
var fs = require('fs');// 引入fs 模块

var limit = true;
var watch = require('watch');
var chokidar = require('chokidar');
const WebSocket = require('ws');

const {createServer} = require('http');
const {createServerFrom} = require('wss');

const http = createServer();

createServerFrom(http, function connectionListener(ws) {
    ws.send('welcome!');
    // console.log("ok")

    var watcher = chokidar.watch('file, dir, or glob', {
        ignored: /[\/\\]\./, persistent: true
    });

    var log = console.log.bind(console);
    console.log("new");
    watcher
        .on('add', function (path) {
            log('File', path, 'has been added');
        })
        .on('addDir', function (path) {
            log('Directory', path, 'has been added');
        })
        .on('change', function (path) {
            // if(~path.indexOf(".idea")){
            //         return;
            //     }
            log('File', path, 'has been changed');
        })
        .on('unlink', function (path) {
            log('File', path, 'has been removed');
        })
        .on('unlinkDir', function (path) {
            log('Directory', path, 'has been removed');
        })
        .on('error', function (error) {
            log('Error happened', error);
        })
        .on('ready', function () {
            log('Initial scan complete. Ready for changes.');
        })
        .on('raw', function (event, path, details) {
            if (( ~path.indexOf("css") || ~path.indexOf("html") || ~path.indexOf("js") ) && limit) {
                console.log(new Date());
                //不知为何 会自己 触发4次 加个限制
                limit = false;
                setTimeout(function () {
                    limit = true;
                    ws.send("wx")
                }, 500)
            }
            // log('Raw event info:', event, path, details);
        });

    ws.on('message', (data) => {
        ws.send("reload")       //echo-server
    })
    ws.on("error",function (e) {
        console.log('WebSocket发生错误: ' + e.code)
        console.log(e);
        // ws.close(); //关闭TCP连接
    });

})
.listen(7000, function () {
  const {address, port} = this.address() // this is the http[s].Server 
  console.log('listening on http://%s:%d (%s)', /::/.test(address) ? '0.0.0.0' : address, port)// http.listen(7000);
})
//检查文件 是否改变
